<template>
  <div class="hello">
    <h1>Koa - Demo</h1>
    <!-- <div class="hello-ctr">
      <input v-model="id">
      <button @click="add(id)">增加</button>
      <button @click="del(id)">删除</button>
      <button @click="get(id)">获取</button>
      <button @click="getList">列表</button>
    </div> -->
    <!-- <textarea v-model="msg"></textarea> -->
    <div class="list-wrapper">
      <p v-for="v in msgArr" :key="v">{{v}}</p>
    </div>
    <div class="msg-wrapper">
      <input v-model="nickName">
      <input v-model="msg">
      <button @click="send">发送</button>
    </div>
  </div>
</template>

<script>
import {getMsgList} from '@/services/api'
import io from 'socket.io-client'
export default {
  name: 'hello',
  data () {
    return {
      nickName: 'Chris',
      msg: '',
      msgArr: [],
      id: 1,
      socket: ''
    }
  },
  methods: {
    async send () {
      let userId = 2
      let content = this.msg
      let createTime = new Date()
      this.socket.emit('chat', {userId, content, createTime})
      this.msg = ''
    },
    async loadData (params) {
      await getMsgList()
    }
  },
  created () {
    this.loadData()
    this.socket = io.connect('http://localhost:3000')
    let $this = this
    this.socket.on('chat', data => {
      $this.msgArr.push(`${$this.nickName}: ${data.content}`)
    })
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
P {
  margin: 0;
  padding: 0;
}
.hello {
  width: 100%;
  height: 100%;
}
.list-wrapper {
  text-align: left;
  border: 1px solid #000000;
}
.msg-wrapper {
  margin-top: 1rem;
  text-align: right;
}
</style>
